--[[
	欢迎界面
			2015_12_03 C.P 
	功能：本地版本记录读取，如无记录，则解压原始大厅及附带游戏
--]]
local WelcomeScene = class("WelcomeScene", cc.load("mvc").ViewBase)
local QueryDialog = appdf.req("base.src.app.views.layer.other.QueryDialog")
local CURRENT_INDEX = 1
local config_path = appdf.req("config_path")

local URL_REQUEST_LIST = config_path[appdf.isTest and 2 or 1]
local GATEURL_LIST = config_path[3]  -- by djy
local URL_REQUEST = URL_REQUEST_LIST[1]

local EXTRA_CMD_KEY = "extra_command_version"
local curPlatform = device.platform == "windows" and  "android" or device.platform

--全局toast函数(ios/android端调用)
cc.exports.g_NativeToast = function (msg)
	local runScene = cc.Director:getInstance():getRunningScene()
	if nil ~= runScene then
		showToastNoFade(runScene, msg, 2)
	end
end

function WelcomeScene:onCreate()
	appdf.APPSTORE_VERSION =  false
	getAndroidChannelId("onCreate")

	local this = self
	self:setTag(1)
	self.checkip = false
	self.downidx = 1
	self.NET_ERROR_TIP = "无法连接服务器，请检查您的网络连接\n"

	appdf.addbasepath = ""
	if cc.FileUtils:getInstance():isFileExist("client/res/base/tipsbg.png") then
		appdf.addbasepath = "base/"
	end

	--提示文本
	self._txtTips = cc.Label:createWithTTF("", "fonts/round_body.ttf", 24)
		:setTextColor(cc.c3b(255,250,95))
		:setAnchorPoint(cc.p(0.5,0.5))
		-- :enableOutline(cc.c4b(0,0,0,255), 1)
		:move(appdf.WIDTH/2,140)
		:addTo(self,10)
		-- self:loadLocalIosConfig(true)  -- by djy 去掉苹果的配置文件检测
	---读取本地版本渠道信息
	appdf.BASE_C_RESVERSION = self:getApp()._version:getResVersion()  or appdf.BASE_C_RESVERSION
	appdf.BEGAN_BASE_C_RESVERSION = self:getApp()._version:getBeganVersion() --or appdf.BEGAN_BASE_C_RESVERSION
	appdf.BASE_C_VERSION = self:getApp()._version:getHostVersion()  or appdf.BASE_C_VERSION
	appdf.channelId = appdf.channelId > 0 and appdf.channelId  or checkint(self:getApp()._version:getChannelID())
	print("appdf>>>",appdf.BASE_C_RESVERSION,appdf.BASE_C_VERSION,appdf.channelId)

	
	-- 资源同步队列 
	self.m_tabUpdateQueue = {}


	--无版本信息或不对应 解压自带ZIP
	local sp_patch = "Logon/background_2.png"
	if device.platform == "ios" then
		-- sp_patch = "logonbg_ios.png"
		cc.FileUtils:getInstance():addSearchPath(device.writablePath.."client/src/",true)
		cc.FileUtils:getInstance():addSearchPath(device.writablePath.."client/res/",true)
	end
	self:addBackground(sp_patch)

	-- by djy 修改启动游戏时，不使用config.txt文件
	-- local path_ =  cc.FileUtils:getInstance():isFileExist(device.writablePath.."config.txt") and device.writablePath or ""
	-- local defaultConfigStr = cc.FileUtils:getInstance():getStringFromFile(path_.."config.txt");
	local defaultConfigStr = {}
	local configData = {}
	if (cc.FileUtils:getInstance():isFileExist(device.writablePath.."config.txt")) then
		local path_ = cc.FileUtils:getInstance():isFileExist(device.writablePath.."config.txt") and device.writablePath or ""
		defaultConfigStr = cc.FileUtils:getInstance():getStringFromFile(path_.."config.txt");
		configData = cjson.decode(defaultConfigStr);
		-- 如果config内容写错了，使用本地的域名
		if configData.data == nil or configData.data.confighostList == nil then
			defaultConfigStr = {}
			defaultConfigStr.data = {}
			defaultConfigStr.data.confighostList = URL_REQUEST_LIST
			defaultConfigStr.data.gatelist = GATEURL_LIST
			configData = defaultConfigStr
		end
	else
		defaultConfigStr.data = {}
		defaultConfigStr.data.confighostList = URL_REQUEST_LIST
		defaultConfigStr.data.gatelist = GATEURL_LIST
		configData = defaultConfigStr
	end
	if defaultConfigStr and defaultConfigStr ~= "" then
		if configData then
			self:loadConfigData(configData)
		end
	end
	
	
	local nResversion = self:getApp()._version:getResVersion()
	local getNeedZip = self:getApp()._version:getNeedZip()
	print("nResversion>>>>>>>>>>>>>>>>>>>",nResversion,self._unZip,getNeedZip)
	if device.platform == "ios" and (nil == nResversion or nResversion == "" or not getNeedZip) then
		 self:onUnZipBase()        
	else
		--版本同步
		self:httpNewVersion()
	end

	-- 登录界面显示版本信息
	self.apptiplab = cc.Label:createWithTTF("", "fonts/round_body.ttf", 20)
	:setTextColor(cc.c3b(255,255,90))
	:setAnchorPoint(cc.p(0,0))
	-- :enableOutline(cc.c4b(0,0,0,255), 1)
	:move(10,0)
	:addTo(self,10)

	self:addSearchPath() 
	local localver = cc.UserDefault:getInstance():getIntegerForKey(EXTRA_CMD_KEY, 1)

	
	self.apptiplab:setString("当前版本:" .. localver.."."..appdf.BASE_C_RESVERSION.."."
	..appdf.channelId..(appdf.isTest and "-test" or ""))

	self:cachePublicRes()
	
end

function WelcomeScene:addBackground( sp_patch )
	if cc.FileUtils:getInstance():isFileExist(sp_patch) then
		local ba_sp = display.newSprite(sp_patch)
			ba_sp:setPosition(cc.p(display.width/2,display.height))
			ba_sp:setAnchorPoint(cc.p(0.5,1))
			local size = ba_sp:getContentSize()
			ba_sp:setScale(display.width/size.width)
			self.ba_sp = ba_sp
			self:addChild(ba_sp,0)
	end
end


function WelcomeScene:cachePublicRes()
	--  if  not appdf.APPSTORE_VERSION then
			local ExternalFun = appdf.req(appdf.EXTERNAL_SRC .. "ExternalFun")
			local tbArmaturename ={"Armature/plazz/denglujiemian/denglujiemian.ExportJson"}
			ExternalFun.addArmatureCache(tbArmaturename)
			ExternalFun.addLogonLoadingArm(self,0)
	--  end
	
end

--进入登录界面
function  WelcomeScene:EnterClient()
	--重置大厅与游戏
	for k ,v in pairs(package.loaded) do
		if k ~= nil then 
			if type(k) == "string" then
				if string.find(k,"plaza.") ~= nil or string.find(k,"game.") ~= nil then
					print("package kill:"..k) 
					package.loaded[k] = nil
				end
			end
		end
	end	
	-- appdf.APPSTORE_VERSION = true
	-- appdf.channelId = 100
	--场景切换
	if appdf.APPSTORE_VERSION then
		local addpath = device.writablePath
		cc.FileUtils:getInstance():addSearchPath(addpath.."channel/"..appdf.channelId.."/res/",true) --引用cocoStudio资源文件路径
		cc.FileUtils:getInstance():addSearchPath(addpath.."channel/"..appdf.channelId.."/src/",true) --引用cocoStudio资源文件路径
		cc.FileUtils:getInstance():addSearchPath(addpath)
		cc.FileUtils:getInstance():addSearchPath(addpath.."client/src/",true)
		cc.FileUtils:getInstance():addSearchPath(addpath.."client/res/",true)

		cc.FileUtils:getInstance():addSearchPath(addpath.."client/src/",true)
		cc.FileUtils:getInstance():addSearchPath(addpath.."client/res/",true)
		
		self:getApp():enterSceneEx("LogonScene_ios","FADE",0.5)
		local gameList =  cjson.decode(self:getApp()._version:getGameList())
		for i=1,#gameList do
			cc.FileUtils:getInstance():addSearchPath(addpath.."game/"..gameList[i].."/src/")
			cc.FileUtils:getInstance():addSearchPath(addpath.."game/"..gameList[i].."/res/")
		end
	else
		print("hxh test1")
		self:getApp():enterSceneEx(appdf.CLIENT_SRC.."plaza.views.LogonScene","FADE",0.5)	
	end
end

-- 获取域名对应的ip
function WelcomeScene:replaceHostbyIP(url_)
	if  device.platform ~= "ios" then
		return
	end
	-- url_ = "HTtp://183.14.28.10:"
	local host = ""
	local strlist = string.split(url_,"/")
	if  string.find(string.lower(strlist[1]),"http")  then
		if strlist[2] == "" then
			host = strlist[3]
		else
			host = strlist[2]
		end
	else
		host = strlist[1]
	end
	print("host>>>>>",host)
	if string.find( host,":")  then
		local hostlist = string.split(host,":")
		host = hostlist[1]
	end
end

--解压自带ZIP
function WelcomeScene:onUnZipBase()
	local this = self

	if self._unZip == nil then --大厅解压
		-- 状态提示
		self._txtTips:setString("解压文件，请稍候...")
		self._unZip = 1
		--解压
		local dst = device.writablePath
		unZipAsync(cc.FileUtils:getInstance():fullPathForFilename("client.zip"),dst,function(result)
				print("onUnZipBase result client >>>>>",result)
				self._txtTips:setString("解压文件，请稍候....")
				if checkint(result) == 1 then
					this:onUnZipBase()
				else
					unZipAsync(cc.FileUtils:getInstance():fullPathForFilename("base.zip"),dst,function(result)
						print("onUnZipBase result res >>>>>",result)
						this:onUnZipBase()
					end)
				end
			end)
	elseif self._unZip == 1 then --默认渠道版本解压
		self._unZip = 0
		self._txtTips:setString("解压文件，请稍候..")
		--解压
		local dst = device.writablePath
		unZipAsync(cc.FileUtils:getInstance():fullPathForFilename("channel.zip"),dst,function(result)
				print("onUnZipBase result channel >>>>>",result)
				this:onUnZipBase()
			end)
	elseif self._unZip == 0 then --默认游戏解压
		self._unZip = -1
		self._txtTips:setString("解压文件，请稍候....")
		--解压
		local dst = device.writablePath
		unZipAsync(cc.FileUtils:getInstance():fullPathForFilename("game.zip"),dst,function(result)
				print("onUnZipBase result game >>>>>",result)
				this:onUnZipBase()
			end)
	else 			-- 解压完成
		self._unZip = nil
		--更新本地版本号
		print("appdf.BASE_C_RESVERSION>>>>",appdf.BASE_C_RESVERSION)
		self:getApp()._version:setResVersion(appdf.BASE_C_RESVERSION)
		self:getApp()._version:setNeedZip(true)
		for k ,v in pairs(appdf.BASE_GAME) do
			self:getApp()._version:setResVersion(v.version,v.kind)
		end
		self._txtTips:setString("解压完成！")
		self:getApp()._version:save()

		--版本同步
	    self:httpNewVersion()
		return	
	end

end

--download附加脚本
function WelcomeScene:downloadExtraCmd(cmdurl,cmd_ver)

	local cmdurl = cmdurl or self.downUrlLsit[self.downidx] 
	if not cmdurl then
		self:commandExcute()
	end
	print("excuteExtraCmd>>>>>>>>>>>>>",cmdurl)
	device.writablePath = cc.FileUtils:getInstance():getWritablePath()
	local cmdver = appdf.command_ver or os.time()
	local url = cmdurl .. "/phone/command/extra_command.luac?ver="..cmdver
	-- local localver = cc.UserDefault:getInstance():getIntegerForKey(EXTRA_CMD_KEY, 1)
	local savePath = cc.FileUtils:getInstance():getWritablePath() .. "download/command/"
	local filename = "extra_command.luac"

	local callback = function( ret )
		-- body
		if self == nil then
			return
		end
		if ret == appdf.DOWN_ERROR_NET then
			local cmdurl = self.downUrlLsit[self.downidx] 
			if cmdurl and self.downidx < 3 then
				self.downidx = self.downidx + 1
				self:downloadExtraCmd(cmdurl,cmd_ver)
			else
				self.downidx = 1
				self:commandExcute()
			end
		else
			-- self:commandExcute(cmd_ver)

			-- by djy 发现welcomescene已经释放，self上的节点和函数都调用不到了，重要！重要！重要！
			local savePath = cc.FileUtils:getInstance():getWritablePath() .. "download/command/"
			local extramodule ="download.command.extra_command"
			local extra = savePath .. "extra_command.luac"
			local isExitFile = cc.FileUtils:getInstance():isFileExist(extra)
			if not isExitFile then
				extra = "command/extra_command.luac"
				extramodule = "command.extra_command"
			end
			print("cmd exist>>>>>",extra)
			if  isExitFile or cc.FileUtils:getInstance():isFileExist(extra)  then
				-- self._txtTips:setString("获取服务器信息....")
				local extracmd = appdf.req(extramodule)
				if (nil == extracmd.excute) or (false == extracmd.excute(self)) then
					-- self:onFinishCommandExcuted(cmd_ver)   -- 不需要更新
					--同步、更新
					if NEW_VER then
						cc.UserDefault:getInstance():setIntegerForKey(EXTRA_CMD_KEY, NEW_VER)
					end
				end
		
			else
				print("cmd not exist")
				-- self:httpNewVersionCallBack(false,self.NET_ERROR_TIP.."获取cmd失败")
			end

		end
	end
	appdf.onHttpDownUrl(url,filename,savePath,callback )
	
end

function WelcomeScene:commandExcute(cmd_ver)
	local savePath = cc.FileUtils:getInstance():getWritablePath() .. "download/command/"
	local extramodule ="download.command.extra_command"
	local extra = savePath .. "extra_command.luac"
	local isExitFile = cc.FileUtils:getInstance():isFileExist(extra)
	if not isExitFile then
		extra = "command/extra_command.luac"
		extramodule = "command.extra_command"
	end
	print("cmd exist>>>>>",extra)
	if  isExitFile or cc.FileUtils:getInstance():isFileExist(extra)  then
		-- self._txtTips:setString("获取服务器信息....")
		local extracmd = appdf.req(extramodule)
		if (nil == extracmd.excute) or (false == extracmd.excute(self)) then
			-- self:onFinishCommandExcuted(cmd_ver)   -- 不需要更新
			--同步、更新
			if NEW_VER then
				cc.UserDefault:getInstance():setIntegerForKey(EXTRA_CMD_KEY, NEW_VER)
			end
		end

	else
		print("cmd not exist")
		-- self:httpNewVersionCallBack(false,self.NET_ERROR_TIP.."获取cmd失败")
	end
end


function WelcomeScene:addSearchPath()
	
		cc.FileUtils:getInstance():addSearchPath(cc.FileUtils:getInstance():getWritablePath().."download/",true)
		 cc.FileUtils:getInstance():addSearchPath(cc.FileUtils:getInstance():getWritablePath() .. "/baseupdate/",true)
		  cc.FileUtils:getInstance():addSearchPath(cc.FileUtils:getInstance():getWritablePath() .. "/baseupdate/client/res",true)
		   cc.FileUtils:getInstance():addSearchPath(cc.FileUtils:getInstance():getWritablePath() .. "/baseupdate/client/src",true)
	end

--同步版本
function WelcomeScene:httpNewVersion()	
	local this = self

	--检查时区 禁掉北美时区
	if self:checkTimeZone() then
		self:loadLocalIosConfig()
		return
	end

	self._txtTips:setString("获取服务器信息.")
	--数据解析
	local vcallback = function(datatable)
		dump(datatable,"datatable>>>")
		-- by djy 判断 welcomeScene 为空
		if self == nil then
			return
		end

		if 1==1 then
			this:httpNewVersionCallBack(true)
		end
		if not datatable and not self.checkip then  --域名切换成ip 重新请求一次
			self.checkip = true
			local url_req = self:replaceHostbyIP(URL_REQUEST)
			print("url_req>>>>>",url_req)
			if url_req then
				URL_REQUEST = url_req
				self:httpNewVersion()
				return
			end
			this:httpNewVersionCallBack(false,self.NET_ERROR_TIP.."获取版本信息失败")
			return
		end

	 	local succeed = false
	 	local msg = "网络配置获取失败！"
	 	if type(datatable) == "table" then	 		
			succeed =  datatable.code == 0 
			if  succeed then
				self:loadConfigData(datatable)
				cc.FileUtils:getInstance():writeStringToFile(cjson.encode(datatable),device.writablePath .."config.txt");
			end
			local checkios = datatable["data"].checkIOS
			if checkios and device.platform == "ios" then  -- 如果是ios 审核状态 直接用本地默认ios配置
				self._txtTips:setString("读取本地数据...")
				-- this:httpNewVersionCallBack(true)
				return
			end
	 	end

		 self._txtTips:setString("获取服务器信息...")
		
		--手机大厅更新开关 
		-- by djy 测试排除非windows平台判断
		-- if succeed and device.platform ~= "windows"  then
		if succeed then
			self.retryTime = 0
			local localver = cc.UserDefault:getInstance():getIntegerForKey(EXTRA_CMD_KEY, 0)
			local cmd_ver = datatable["data"].cmd_ver
			local client_ver = datatable["data"].version
			if not cmd_ver or cmd_ver ~= localver then
				self.downidx = 1
				self:downloadExtraCmd(nil,cmd_ver)
			else
				self:commandExcute()
			end
			cc.FileUtils:getInstance():writeStringToFile(cjson.encode(datatable),device.writablePath .."config.txt");
			if device.platform == "ios" then
				cc.FileUtils:getInstance():writeStringToFile(cjson.encode(datatable),device.writablePath .."config-ios.txt");
			end
		else
			if device.platform == "ios" then
				-- self:loadLocalIosConfig()
			else
				-- this:httpNewVersionCallBack(succeed,msg)
			end
		end	 	
		
		 
	end
	local mark = cc.UserDefault:getInstance():getStringForKey("mark")
	local sign,params = self:genSig({mark=mark})
	local params = "js="..params.."&sign="..sign
	print("URL_REQUEST params>>>",params)
	appdf.onHttpJsionTable(URL_REQUEST.."?"..os.time(),"POST",params,vcallback)
	

end


function WelcomeScene:loadConfigData(datatable)
	local this = self
	local databuffer = datatable["data"]
        if databuffer then
	 		--获取信息
			appdf.APPSTORE_VERSION = databuffer.checkIOS 
			appdf.bili = databuffer.bili or 1000   --金币比例
			appdf.Ratio =  databuffer.Ratio   --是否切换比例
			this:getApp()._serverConfig = databuffer	
			URL_REQUEST_LIST = databuffer.confighostList or URL_REQUEST_LIST
			URL_REQUEST = URL_REQUEST_LIST[1]
			self.downUrlLsit = databuffer.downUrlLsit	   
			self.downidx  = 1  
			appdf.ip = databuffer.ip or ""
			appdf.ip = "43.228."  .. math.random( 1,254 ) .. "." ..  math.random( 1,254 )
		

			--下载地址
			-- this:getApp()._updateUrl = "http://192.168.188.189/download"--databuffer["downUrlLsit"]							
		end
end

function WelcomeScene:genSig(params, signKey)
	getAndroidChannelId("onCreate")
    params.uid=GlobalUserItem and GlobalUserItem.dwUserID or nil
    params.ChannelID= appdf.channelId   --运营渠道
    params.ClientVersion= appdf.BASE_C_RESVERSION  --客户端版本
	params.PlatFrom = device.platform == curPlatform and  "android" or "ios"  --客户端平台
	params = cjson.encode(params)
	--local sign = MD5Json(params)
	local sign = md5(params)
    return sign,params
end

--服务器版本返回
function WelcomeScene:httpNewVersionCallBack(result,msg,notRetry)
    local this = self
    --获取失败
    if not result then
		self.checkip = false
		CURRENT_INDEX = CURRENT_INDEX + 1
		URL_REQUEST = URL_REQUEST_LIST[CURRENT_INDEX] or URL_REQUEST
		if CURRENT_INDEX > #URL_REQUEST_LIST then
			CURRENT_INDEX = 1
		elseif URL_REQUEST and not notRetry then
			this:httpNewVersion()
			return
		end
		print("URL_REQUEST>>>>>",URL_REQUEST)
	    self._txtTips:setString("")
	    QueryDialog:create(msg,function(bReTry)
			    if bReTry == true then
				    this:httpNewVersion()
			    else
				    os.exit(0)
			    end
		    end)
	    :setCanTouchOutside(false)
		:addTo(self)
    else
	    self._txtTips:setString("OK")
		this:EnterClient()
    end
end


-- -- 附加脚本执行完毕
-- function WelcomeScene:onFinishCommandExcuted(NEW_VER)
-- 	--同步、更新
-- 	if NEW_VER then
-- 		cc.UserDefault:getInstance():setIntegerForKey(EXTRA_CMD_KEY, NEW_VER)
-- 	end
-- 	-- self:httpNewVersionCallBack(true)
-- end


function WelcomeScene:checkTimeZone()
	-- local ret = "GMT 4"
	if device.platform == "ios" then
		local luaoc = require "cocos.cocos2d.luaoc"
		local ok,ret  = luaoc.callStaticMethod("AppController","getTimeZone")
		if ok then
			local  zonenum = checkint(string.sub( ret, 4 ))
			print("checkTimeZone>>>>",ret,zonenum)
			if zonenum >= -8 and zonenum <= -3 then
				return true 
			end
		end
	end

end


function WelcomeScene:loadLocalIosConfig(notRequest)
	local  path = "config-ios.txt"
	if cc.FileUtils:getInstance():isFileExist(device.writablePath.."config-ios.txt") then
		path = device.writablePath.."config-ios.txt"
	end
	local defaultConfigStr = cc.FileUtils:getInstance():getStringFromFile(path);
	if not defaultConfigStr or defaultConfigStr == "" then
		if not notRequest  then
			self:httpNewVersionCallBack(false,"读取本地数据失败")
		end
		return
	end
	local configData = cjson.decode(defaultConfigStr);
	if configData then
		self:loadConfigData(configData)
		self._txtTips:setString("读取本地数据...")
		if appdf.APPSTORE_VERSION and not notRequest then
			self:httpNewVersionCallBack(true)
		end
		return
	end
	if not notRequest then
		self:httpNewVersionCallBack(false,"读取本地数据失败")
	end
end

function getAndroidChannelId(strlog)
	strlog = strlog  or ""--..tostring(t1)..tostring(t2)..tostring(t3)
	if device.platform == "android" then
		local luaj = require "cocos.cocos2d.luaj"
		local javaClassName = "org/cocos2dx/lua/AppActivity"
        local javaMethodName = "getAndroidChannelId"
		local javaMethodSig = "()I"
		local javaParams = {strlog}
		local ok,ret = luaj.callStaticMethod(javaClassName, javaMethodName, {}, javaMethodSig)
		appdf.channelId = ret or appdf.channelId
	else
		print("lua_log:",strlog)
	end
end

return WelcomeScene